
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>自定义模板的后端 &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="next" title="自定义模板标签和过滤器" href="custom-template-tags.html" />
    <link rel="prev" title="自定义查询器" href="custom-lookups.html" />



 
<script src="../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="custom-lookups.html" title="自定义查询器">previous</a>
     |
    <a href="index.html" title="操作指南" accesskey="U">up</a>
   |
    <a href="custom-template-tags.html" title="自定义模板标签和过滤器">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="howto-custom-template-backend">
            
  <div class="section" id="s-custom-template-backend">
<span id="custom-template-backend"></span><h1>自定义模板的后端<a class="headerlink" href="#custom-template-backend" title="永久链接至标题">¶</a></h1>
<div class="section" id="s-custom-backends">
<span id="custom-backends"></span><h2>自定义后端<a class="headerlink" href="#custom-backends" title="永久链接至标题">¶</a></h2>
<p>以下是如何实现一个在另一个模板系统中使用的自定义后端。一个模板后端是继承自后端基本类 <code class="docutils literal notranslate"><span class="pre">django.template.backends.base.BaseEngine</span></code> 。它必须实现 <code class="docutils literal notranslate"><span class="pre">get_template()</span></code> 和可选实现 <code class="docutils literal notranslate"><span class="pre">from_string()</span></code> 。以下是一个模拟 <code class="docutils literal notranslate"><span class="pre">foobar</span></code> 模板库的例子。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.template</span> <span class="kn">import</span> <span class="n">TemplateDoesNotExist</span><span class="p">,</span> <span class="n">TemplateSyntaxError</span>
<span class="kn">from</span> <span class="nn">django.template.backends.base</span> <span class="kn">import</span> <span class="n">BaseEngine</span>
<span class="kn">from</span> <span class="nn">django.template.backends.utils</span> <span class="kn">import</span> <span class="n">csrf_input_lazy</span><span class="p">,</span> <span class="n">csrf_token_lazy</span>

<span class="kn">import</span> <span class="nn">foobar</span>


<span class="k">class</span> <span class="nc">FooBar</span><span class="p">(</span><span class="n">BaseEngine</span><span class="p">):</span>

    <span class="c1"># Name of the subdirectory containing the templates for this engine</span>
    <span class="c1"># inside an installed application.</span>
    <span class="n">app_dirname</span> <span class="o">=</span> <span class="s1">&#39;foobar&#39;</span>

    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">params</span><span class="p">):</span>
        <span class="n">params</span> <span class="o">=</span> <span class="n">params</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
        <span class="n">options</span> <span class="o">=</span> <span class="n">params</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">&#39;OPTIONS&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="n">params</span><span class="p">)</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">engine</span> <span class="o">=</span> <span class="n">foobar</span><span class="o">.</span><span class="n">Engine</span><span class="p">(</span><span class="o">**</span><span class="n">options</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">from_string</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">template_code</span><span class="p">):</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">Template</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">engine</span><span class="o">.</span><span class="n">from_string</span><span class="p">(</span><span class="n">template_code</span><span class="p">))</span>
        <span class="k">except</span> <span class="n">foobar</span><span class="o">.</span><span class="n">TemplateCompilationFailed</span> <span class="k">as</span> <span class="n">exc</span><span class="p">:</span>
            <span class="k">raise</span> <span class="n">TemplateSyntaxError</span><span class="p">(</span><span class="n">exc</span><span class="o">.</span><span class="n">args</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">get_template</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">template_name</span><span class="p">):</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">Template</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">engine</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="n">template_name</span><span class="p">))</span>
        <span class="k">except</span> <span class="n">foobar</span><span class="o">.</span><span class="n">TemplateNotFound</span> <span class="k">as</span> <span class="n">exc</span><span class="p">:</span>
            <span class="k">raise</span> <span class="n">TemplateDoesNotExist</span><span class="p">(</span><span class="n">exc</span><span class="o">.</span><span class="n">args</span><span class="p">,</span> <span class="n">backend</span><span class="o">=</span><span class="bp">self</span><span class="p">)</span>
        <span class="k">except</span> <span class="n">foobar</span><span class="o">.</span><span class="n">TemplateCompilationFailed</span> <span class="k">as</span> <span class="n">exc</span><span class="p">:</span>
            <span class="k">raise</span> <span class="n">TemplateSyntaxError</span><span class="p">(</span><span class="n">exc</span><span class="o">.</span><span class="n">args</span><span class="p">)</span>


<span class="k">class</span> <span class="nc">Template</span><span class="p">:</span>

    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">template</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">template</span> <span class="o">=</span> <span class="n">template</span>

    <span class="k">def</span> <span class="nf">render</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">context</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">request</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">context</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">context</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="k">if</span> <span class="n">request</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">context</span><span class="p">[</span><span class="s1">&#39;request&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">request</span>
            <span class="n">context</span><span class="p">[</span><span class="s1">&#39;csrf_input&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">csrf_input_lazy</span><span class="p">(</span><span class="n">request</span><span class="p">)</span>
            <span class="n">context</span><span class="p">[</span><span class="s1">&#39;csrf_token&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">csrf_token_lazy</span><span class="p">(</span><span class="n">request</span><span class="p">)</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">template</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">context</span><span class="p">)</span>
</pre></div>
</div>
<p>请参阅 <a class="reference external" href="https://github.com/django/deps/blob/main/final/0182-multiple-template-engines.rst">DEP 182</a> 以获取更多信息。</p>
</div>
<div class="section" id="s-debug-integration-for-custom-engines">
<span id="s-template-debug-integration"></span><span id="debug-integration-for-custom-engines"></span><span id="template-debug-integration"></span><h2>为自定义引擎集成调试功能<a class="headerlink" href="#debug-integration-for-custom-engines" title="永久链接至标题">¶</a></h2>
<p>当模板有错误时Django调试页面会提供相应的钩子信息。自定义后端引擎能使用这些钩子来细化显示给用户的回溯信息。以下是可用的钩子：</p>
<div class="section" id="s-template-postmortem">
<span id="s-id1"></span><span id="template-postmortem"></span><span id="id1"></span><h3>模板剖析<a class="headerlink" href="#template-postmortem" title="永久链接至标题">¶</a></h3>
<p>当错误 <a class="reference internal" href="../topics/templates.html#django.template.TemplateDoesNotExist" title="django.template.TemplateDoesNotExist"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TemplateDoesNotExist</span></code></a> 发生时显示剖析。它会列举出尝试查找指定模板时使用的模板引擎和加载器。举个例子，如果配置了两个Django引擎，剖析显示如下：</p>
<img alt="../_images/postmortem.png" src="../_images/postmortem.png" />
<p>当 <a class="reference internal" href="../topics/templates.html#django.template.TemplateDoesNotExist" title="django.template.TemplateDoesNotExist"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TemplateDoesNotExist</span></code></a> 错误触发时自定义引擎会填写 <code class="docutils literal notranslate"><span class="pre">后端</span></code> 和 <code class="docutils literal notranslate"><span class="pre">尝试</span></code> 参数。使用剖析 :ref:` 的后端必须要指定模板对象上的一个来源 1` 。</p>
</div>
<div class="section" id="s-contextual-line-information">
<span id="contextual-line-information"></span><h3>上下文信息<a class="headerlink" href="#contextual-line-information" title="永久链接至标题">¶</a></h3>
<p>当模板解析或渲染时发生错误，Django会显示错误所在的行。举个例子：</p>
<img alt="../_images/template-lines.png" src="../_images/template-lines.png" />
<p>在解析或渲染异常中配置了 <code class="docutils literal notranslate"><span class="pre">template_debug</span></code> 属性的自定义引擎会显示这条信息。这个属性是一个有以下值的类 <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#dict" title="(在 Python v3.10)"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>：</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">'name'</span></code> ：发生异常的模板名称</li>
<li><code class="docutils literal notranslate"><span class="pre">'message'</span></code>: 异常信息。</li>
<li><code class="docutils literal notranslate"><span class="pre">'source_lines'</span></code>: 异常发生的行及其前后内容。这是为了上下文，所以它不应该超过二十行。</li>
<li><code class="docutils literal notranslate"><span class="pre">'line'</span></code>: 异常发生的行数。</li>
<li><code class="docutils literal notranslate"><span class="pre">'before'</span></code>: 发生错误的标识符的错误行前面的内容。</li>
<li><code class="docutils literal notranslate"><span class="pre">'during'</span></code>: 发生错误的标识符。</li>
<li><code class="docutils literal notranslate"><span class="pre">'after'</span></code>: 发生错误的标识符的错误行后面的内容。</li>
<li><code class="docutils literal notranslate"><span class="pre">'total'</span></code>: <code class="docutils literal notranslate"><span class="pre">source_lines</span></code> 总行数。</li>
<li><code class="docutils literal notranslate"><span class="pre">'top'</span></code>: <code class="docutils literal notranslate"><span class="pre">source_lines</span></code> 起始行数。</li>
<li><code class="docutils literal notranslate"><span class="pre">'bottom'</span></code>: <code class="docutils literal notranslate"><span class="pre">source_lines</span></code> 结束的行数。</li>
</ul>
<p>根据上述模板错误， <code class="docutils literal notranslate"><span class="pre">template_debug</span></code> 会像这样：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">{</span>
    <span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;/path/to/template.html&#39;</span><span class="p">,</span>
    <span class="s1">&#39;message&#39;</span><span class="p">:</span> <span class="s2">&quot;Invalid block tag: &#39;syntax&#39;&quot;</span><span class="p">,</span>
    <span class="s1">&#39;source_lines&#39;</span><span class="p">:</span> <span class="p">[</span>
        <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;some</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;lines</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;before</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;Hello {</span><span class="si">% s</span><span class="s1">yntax error %} {{ world }}</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="s1">&#39;some</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="mi">6</span><span class="p">,</span> <span class="s1">&#39;lines</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="mi">7</span><span class="p">,</span> <span class="s1">&#39;after</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="mi">8</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">),</span>
    <span class="p">],</span>
    <span class="s1">&#39;line&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span>
    <span class="s1">&#39;before&#39;</span><span class="p">:</span> <span class="s1">&#39;Hello &#39;</span><span class="p">,</span>
    <span class="s1">&#39;during&#39;</span><span class="p">:</span> <span class="s1">&#39;{</span><span class="si">% s</span><span class="s1">yntax error %}&#39;</span><span class="p">,</span>
    <span class="s1">&#39;after&#39;</span><span class="p">:</span> <span class="s1">&#39; {{ world }}</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span>
    <span class="s1">&#39;total&#39;</span><span class="p">:</span> <span class="mi">9</span><span class="p">,</span>
    <span class="s1">&#39;bottom&#39;</span><span class="p">:</span> <span class="mi">9</span><span class="p">,</span>
    <span class="s1">&#39;top&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="s-origin-api-and-3rd-party-integration">
<span id="s-template-origin-api"></span><span id="origin-api-and-3rd-party-integration"></span><span id="template-origin-api"></span><h3>原始API和第3方集成<a class="headerlink" href="#origin-api-and-3rd-party-integration" title="永久链接至标题">¶</a></h3>
<p>Django有一个可用  <code class="docutils literal notranslate"><span class="pre">template.origin</span></code> 属性的 <a class="reference internal" href="../ref/templates/api.html#django.template.base.Origin" title="django.template.base.Origin"><code class="xref py py-class docutils literal notranslate"><span class="pre">Origin</span></code></a> 基本对象类。这可以让调试信息显示在 <a href="#id1"><span class="problematic" id="id2">:ref:`template 模板剖析上，同时支持第3方库，例如 `Django Debug Toolbar`_</span></a>。</p>
<p>自定义引擎可以通过创建有以下特定属性的对象来提供自身的 <code class="docutils literal notranslate"><span class="pre">template.origin</span></code> 信息。</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">'name'</span></code>: 模板的完整路径。</li>
<li><code class="docutils literal notranslate"><span class="pre">'template_name'</span></code>: 通过模板加载方法打开的模板的相对路径。</li>
<li><code class="docutils literal notranslate"><span class="pre">'loader_name'</span></code>: 一个可选的以字符串形式指定用来加载模板的文件系统类或函数, e.g. <code class="docutils literal notranslate"><span class="pre">django.template.loaders.filesystem.Loader</span></code>.</li>
</ul>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">自定义模板的后端</a><ul>
<li><a class="reference internal" href="#custom-backends">自定义后端</a></li>
<li><a class="reference internal" href="#debug-integration-for-custom-engines">为自定义引擎集成调试功能</a><ul>
<li><a class="reference internal" href="#template-postmortem">模板剖析</a></li>
<li><a class="reference internal" href="#contextual-line-information">上下文信息</a></li>
<li><a class="reference internal" href="#origin-api-and-3rd-party-integration">原始API和第3方集成</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="custom-lookups.html"
                        title="上一章">自定义查询器</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="custom-template-tags.html"
                        title="下一章">自定义模板标签和过滤器</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/custom-template-backend.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="custom-lookups.html" title="自定义查询器">previous</a>
     |
    <a href="index.html" title="操作指南" accesskey="U">up</a>
   |
    <a href="custom-template-tags.html" title="自定义模板标签和过滤器">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>